<template>
  <div class="codemirror-box" :style="{width: `${width}px`,height: `${height}px`}">
    <textarea ref="tt" class="custom-codemirror"></textarea>
  </div>
</template>
<script>
import {nextTick} from 'vue'
export default {
  name: "CmEditor",
  props: {
    modelValue: {
      default:''
    },
    width: {
      type: Number,
      default: 400
    },
    height: {
      type: Number,
      default: 300
    },
  },
  setup(props,context) {
    const tt = ref(null)
    const editing = ref(false);
    let editor = null;
    watch(
        () => props.modelValue,
        () => {
          let cursor = editor.getCursor();
          // console.log(editing.value,props.modelValue)
          // if(!editing.value){
           editor.setValue(props.modelValue);
          editor.setCursor(cursor)
          //editor.refresh()
            //editor.setCursor({line:editor.lastLine(),ch:0})
          // }
          // editing.value = false;
        }
    )

    onMounted(()=>{
        editor = CodeMirror.fromTextArea(tt.value, {
          mode: "javascript",
          lineNumbers: true,
          styleActiveLine: true,
          matchBrackets: true
        });
      editor.setValue(props.modelValue);
      editor.on("change", function(cm) {
        //editing.value = true;
        context.emit('update:modelValue', cm.getValue());
      });

      nextTick(()=>{
        editor.refresh()
      })
    })
    return {tt}
  }
}
</script>
<style scoped>
.codemirror-box{
  font-size : 13px;
  line-height : 150%;
  border: 1px #ccc solid;
}
code {
  padding: 0 2px;
}
</style>